import {
    Button,
    Form,
    Input,
    Select,
    Space,
    Table,
    InputNumber,
    Typography,
   // Popconfirm,
    message,
    Modal

} from 'antd';
import { useState ,useEffect} from 'react';
import { ExclamationCircleOutlined } from '@ant-design/icons';

import myAxios from "../../../utils/myAixos"
import {
    useNavigate,
} from "react-router-dom"

import "./index.css"
//import { observable } from 'mobx';
const ProductList = () => {
    const [datalenth,setdatalenth]=useState()
    const [originData,setOriginData]=useState([])
    const [datalenth2,setdatalenth2]=useState()
    const [datalenth3,setdatalenth3]=useState()

    const alldata=()=>{
        myAxios({
            url: "/getShopData",
            method:"post",
            data:{
            }
    
        }).then(res=>{
                if(res.data.status===200){
                  setOriginData(res.data.data)
                  setdatalenth(res.data.data.length)
                 let data=res.data.data
                 //上线
                let nwearr=data.filter((item)=>{ 
                      return item.p_status ==='上线'
                  })
                  setdatalenth2(nwearr.length)
                //下线
                let nwearr2=data.filter((item)=>{ 
                    return (item.p_status ==='下线' || item.p_status ==='')
                })
                setdatalenth3(nwearr2.length)
                      
                }else{
                   //跳转到404页面 
                }
        })  
    }
    useEffect (()=>{// 跳转页面渲染数据
        alldata()
    },[]) 
    // 下拉框的函数  下拉框搜索
    const selectChange = (value) => { 
        console.log(value);
        myAxios({
            url: "/shopSear",
            method:"post",
            data:{
                p_shoptype:value
            }
    
        }).then(res=>{
            if(res.data.status===200){
                console.log(res.data.data);
                setOriginData(res.data.data)
                message.success('查询成功')
              }else{
                 //跳转到404页面 
                 message.success(res.data.status)
              }
             
        })
    };

    //点击查询
    let [inputval,setinputval]=useState('')  //要使用useState，不然只计算一次input的值
    const Inputval=(e)=>{
       setinputval(e.target.value)
    }
    const searchPro = () => {
        //console.log(`点击查询`,inputval);
        myAxios({
            url: "/search",
            method:"post",
            data:{
                searchVal:inputval
            }
    
        }).then(res=>{
                if(res.data.status===200){
                  setOriginData(res.data.data)
                }else{
                   //跳转到404页面 
                }
        })
        
       
    }
    //点击添加商品跳转
    const navigate=useNavigate();
    const addPro = () => {
        navigate('/HomePage/addPro')

    }


    //以下是修改表格内容
    const EditableCell = ({
        editing,
        dataIndex,
        title,
        inputType,
        record,
        index,
        children,
        ...restProps
    }) => {
        const inputNode = inputType === 'number' ? <InputNumber /> : <Input />;
        return (
            <td {...restProps}>
                {editing ? (
                    <Form.Item
                        name={dataIndex}
                        style={{
                            margin: 0,

                        }}
                    >
                        {inputNode}
                    </Form.Item>
                ) : (
                    children
                )}
            </td>
        );
    };
    const [form] = Form.useForm();
    //edit 编辑
    const edit = (record) => {
      //  console.log(record);//点击要修改的内容拿到的数据
        navigate('/HomePage/changePro', { state: {record} })
    };

  




    //------------------------设置表格
    const columns = [
        {
            title: '编号',
            dataIndex: 'p_id',
            width: '10%',
            align:"center"
        },
        {
            title: '商品图片',
            dataIndex: 'p_src',
            width: '10%',
            align:"center",
          
           // render: (record) => <img src="../../../../public/bg.jpg" alt="" width="100px" />
            render: (_, record) => (
                <Space size="middle">
                    <img src={'/api'+record.p_src} alt="" />
                </Space>
            ),
        },
        {
            title: '商品名称',
            dataIndex: 'p_name',
            width: '20%',
            align:"center"
        },
        {
            title: '价格',
            dataIndex: 'p_money',
            width: '10%',
            align:"center"
           
        },
        {
            title: '状态',
            dataIndex: 'p_status',
            width: '10%',
            align:"center"
           
        },
        {
            title: '商品类型',
            dataIndex: 'p_shoptype',
            width: '10%',
            align:"center"
          
        },
        {
            title: '销量',
            dataIndex: 'p_sales',
            width: '10%',
            align:"center"
           
        },

        {
            //设置操作
            title: '操作',
            dataIndex: 'operation',
            align:"center",
            render: (_, record) => (
                <Space size="middle">
                  <Typography.Link onClick={() => edit(record)} >编辑</Typography.Link>
                  <Typography.Link onClick={() =>confirm(record)}>删除</Typography.Link>
                </Space>
              ),
        },
    ];


    const mergedColumns = columns.map((col) => {
        if (!col.editable) {
            return col;
        }
        return {
            ...col,
            onCell: (record) => ({
                record,
                dataIndex: col.dataIndex,
                title: col.title,
               // editing: isEditing(record),
            }),
        };
    });

    //复选框删除
    const [selectedRowKeys, setSelectedRowKeys] = useState([]);
    const [loading, setLoading] = useState(false);
    //选择获取商品数据   复选框选择商品的id
    const onSelectChange = (newSelectedRowKeys) => {
        //newSelectedRowKeys 是长度
        setSelectedRowKeys(newSelectedRowKeys);
    };
    const rowSelection = {
        selectedRowKeys,
        onChange: onSelectChange,
    };
    const hasSelected = selectedRowKeys.length > 0;
    
    //以下是删除模态框和删除函数
    const [modal, contextHolder] = Modal.useModal();
    const [open, setOpen] = useState(false);
    const confirm = (re) => {
      modal.confirm({
        title: '系统提示',
        icon: <ExclamationCircleOutlined />,
        content: '是否确认删除',
        okText: '确认',
        cancelText: '取消',
        centered:'true',
        onOk:()=>okmodle(re),
        onCancel:quxiao
      });
    };
    const quxiao=()=>{
        setOpen(false)
    }
      //dele 删除
      const okmodle = (aa) => {
        //aa 是这行表数据
      
        let  nwearr=originData.filter((item)=>{ //过滤出不同于删除行的id，filter会返回一个新数组，这个新数组就是剩下的数据
             return item.p_id!==aa.p_id  
        })
        setOriginData(nwearr)
        myAxios({
            url: "/del",
            method:"post",
            data:{
                p_id:aa.p_id
            }
        }).then(res=>{
            if(res.data.status===200){
                message.success('删除成功')
                setOpen(false)
              }
        })

    }
    //以下是全部删除
    const confirm2 = (re) => {
        modal.confirm({
          title: '系统提示',
          icon: <ExclamationCircleOutlined />,
          content: '是否全部删除',
          okText: '确认',
          cancelText: '取消',
          centered:'true',
          onOk:()=>deleall(),
          onCancel:quxiao
        });
      };
      const deleall=()=>{
        setLoading(true);
      //  console.log(selectedRowKeys);//这是选中的商品id
        let nwearr2=[]
        nwearr2 = originData.filter(a=>{   //filter+some 双重过滤对两个数组去重
	    return ! selectedRowKeys.some(c=>(c===a.p_id))
	   })
          setOriginData(nwearr2)
          myAxios({
            url: "/anyDel",
            method:"post",
            data:{
                idArr:selectedRowKeys
            }
        }).then(res=>{
            if(res.data.status===200){
                console.log(res.data.status);
                message.success('批量删除成功')
                setOpen(false)
                alldata()
              }
             
        }).catch(ss=>{
        })
        // ajax request after empty completing
        setTimeout(() => {//删除成功后，清空选中项
            setSelectedRowKeys([]);
            setLoading(false);
        }, 500);
      }
  
   
    //渲染的内容
    return (
        <div className={"pro-duc"}>
            <header>
                <div className={"pro-duc-head"}>
                    <div > 全部商品 <span style={{color:'red'}}> {datalenth}</span> </div>
                    <div > 已上线   <span style={{color:'blue'}}> {datalenth2}</span></div>
                    <div > 未上线   <span style={{color:'orange'}}> {datalenth3}</span></div>
                </div>

                <div className={"pro-duc-search"}>

                    {/* input框应该有个失焦函数来获取输入框的内容 */}
                    <Input placeholder="商品名称/商品编号" onInput={Inputval}/>
                    <Space >
                        {/* Select应该是选择失焦后发送请求而不是跟input一起点击查询发送请求 */}
                        <Select

                            defaultValue=""
                            style={{
                                width: 140,
                                marginRight: 20
                            }}
                            onChange={selectChange}
                            options={[
                                {
                                    value: '虚拟商品',
                                    label: '虚拟商品',
                                },
                                {
                                    value: '实物商品',
                                    label: '实物商品',
                                },
                                {
                                    value: '积分兑换',
                                    label: '积分兑换',
                                }
                            ]}
                        />
                        <Button type="primary" className={"pro-duc-button1"}
                            onClick={searchPro}
                            style={{
                                width: 80,
                                marginRight: 20
                            }}>查询</Button>


                        <Button type="primary" className={"pro-duc-button2"}
                            onClick={addPro}
                            style={{
                                width: 100,
                                marginRight: 20,

                            }}>添加商品</Button>
                    </Space>



                </div>

            </header>
            <section >
                <Form form={form} component={false}>
                    <Table
                        components={{
                            body: {
                                cell: EditableCell,
                            },
                        }}
                        bordered
                        rowSelection={rowSelection}
                        rowKey={record => record.p_id}
                        dataSource={originData} //渲染数据
                        columns={mergedColumns}
                        rowClassName="editable-row"
                        pagination={{
                           // onChange: cancel,
                            total: 0,
                            defaultPageSize: 5,//默认展示
                            //  showTotal: total => `共 ${total} 条数据`,
                            //  showSizeChanger: true,
                            //  pageSizeOptions: ['5', '10'],
                            //  onShowSizeChange:(current, pageSize)=>this.pageSize = pageSize

                        } }

                    />
                </Form>
                <div className='deleall'>
                    <Button type="primary" onClick={confirm2} disabled={!hasSelected} loading={loading}>
                        批量删除
                    </Button>
                    <span
                        style={{
                            marginLeft: 18,
                        }}
                    >
                        {hasSelected ? `选中 ${selectedRowKeys.length} 条` : ''}
                    </span>
                </div>
            </section>
            {contextHolder}{/* 这个是模态框 */}
         
        </div>
    );
};



export default ProductList;